/**
 * Created with JetBrains PhpStorm.
 * User: root
 * Date: 15.05.13
 * Time: 20:42
 * To change this template use File | Settings | File Templates.
 */
(function($){
    $.fn.tabPagination = function(options){
        var pagename;
        var settings = $.extend({
            limit:10
        },options || {});

        var pages = $(this);
        var segment,firstpage;
        pages.css({float:'left',width:'auto',height:'15px','margin':'0'});

        if(pages.attr('data-pagescount') > 1){

            for(var i=1;i <= pages.attr('data-pagescount');i++){

                segment = $('<span>',{class:'pages_current',style:"cursor:pointer;background-color:#7FBDFA;border:1px solid #072A66;font-size:12px;font-weight:normal;margin:3px;padding:3px 5px;text-decoration:none;width:15px;height:20px;border-radius:2px;"});
                pages.append(segment.text(i).attr('id',i));

                if(i == pages.attr('data-pagescount')){
                    var butPrev = $('<span>',{'id':'prev','class':'tabPagButton',text:'<< Пред.'});
                    var butNext = $('<span>',{'id':'next','class':'tabPagButton',text:'След. >>',style:'margin-left:4px;'});
                    pages.prepend(butPrev);
                    pages.append(butNext);
                }
            }
        }
            if(pages.data('artcount') > 50){

                var pagesCont =$(this);
                var pagesCur = pagesCont.find('span.pages_current');
                if(pagesCur.length > 5){
                    for(var i = 5;i <= pagesCur.length;i++){
                        $(pagesCur[i]).hide();
                    }
                }
            }

        var pagesC = $('<strong>',{style:'text-decoration:underline'}).append(pages.data('pagescount'));
        var pagesA = $('<strong>',{style:'text-decoration:underline'}).append(pages.data('artcount'));
        var totalP = $('<span>',{id:'totalP','class':'pagination_info','text':'Всего страниц: ','style':'padding-right:20px;'}).append(pagesC);
        var totalA = $('<span>',{id:'totalA','class':'pagination_info','text':'Статей: ','style':'padding-left:20px;'}).append(pagesA);
        pages.prepend(totalP);
        pages.append(totalA);
        firstpage = pages.find('span#1').attr('class','activepage').css({'cursor':'text','font-weight':'bold','border-radius':'2px'});

        $('.tabPagButton').click(function(){
            var ap = $(this).parent().find('.activepage');
                  if($(this).attr('id') == 'prev'){
                      if(ap.prev().attr('class') == 'pages_current'){
                          ap.prev().click();
                      }
                  }else if($(this).attr('id') == 'next'){
                      if(ap.next().attr('class') == 'pages_current'){
                          ap.next().click();
                      }
                  }
        });

        $(this).parent().find('.pages_current, .activepage').click(function(){
            var activeCont = $(this).parent().parent().find('#container');
            var pagenumber = $(this).attr('id');
            var contP = $(this).parent().find('.pages_current, .activepage');
            var parid = $(this).parent().attr('id');
               if(pagenumber > 5){
                    var page = parseInt(pagenumber) - 6;

                   $(contP[page]).hide();
                }else{
                    var page  = parseInt(pagenumber)+4;

                    $(contP[page]).hide();
                }

            if(parid == 'pages'){
                pagename = 'main';
            }else if(parid == 'artpages'){
                pagename = 'articles';
            }else if(parid == 'revpages'){
                pagename = 'reviews';
            }

            $(this).parent().find('span.activepage').attr('class','pages_current').css({'cursor':'pointer','font-weight':'normal'}).end().end().attr('class','activepage').css({'cursor':'text','font-weight':'bold'}).show();

            if(pagenumber == '1'){pagenumber = 'first';}

            progressbarAjax(activeCont);
            $.ajax({
                url:'/admin/site/getmainpage',
                dataType:'JSON',
                data:{'pagename':pagename,'startpage':pagenumber,'limit':settings.limit},
                type:'POST',
                success:function(resp){

                    var segment =   $(activeCont).find('.segment');
                    var i = 0;
                    $.each(resp, function(i,elm){
                        var count=0;
                        if(resp.length < 10 ){
                            count = 10 - resp.length
                        }
                        var seg = $(segment[i]);
                        $(segment[i]).show();
                        seg.find('.category').attr({'id':elm.article_id,'data-value':elm.category_name});
                        var score = seg.find('.score').attr({'id':elm.article_id,'data-average':elm.sumscore || 0});
                        if(!elm.sumscore){score.find('.jRatingColor').css('width','0px');}
                        else{score.find('.jRatingColor').css('width',elm.sumscore * 12 +'px');}

                        seg.attr('id',elm.article_id);
                        seg.find('#image').find('img').attr({src:'/images/articles/'+elm.img});
                        seg.find('.created').text(elm.created_dt);
                        var vis = $(segment[i]).find('.visibility').find('option');

                        if(elm.visibility=='yes'){

                            $(vis[0]).val('yes').attr('selected','yes').text('да');
                            $(vis[1]).val('no').text('нет');

                        }else{
                            $(vis[0]).val('no').attr('selected','no').text('нет');
                            $(vis[1]).val('yes').text('да');
                        }

                        var sel = seg.find('.category select option');
                        sel.each(function(i,opt){
                            var optval = $(opt).val()
                            if(optval != elm.category_name){$(opt).removeAttr('selected')}
                            if(optval == elm.category_name){
                               $(opt).attr('selected','selected');
                            }
                        });
                        var com = seg.find('.comments');
                        var img = $('<img>',{id:'imgcomment',src:'/images/nocomment.png',style:'vertical-align:middle;padding-right:3px;'});
                        if(elm.comments > 0){

                            img.attr({src:'/images/comment.png',title:'Комментарии к статье'});
                            com.text(elm.comments).attr('id',elm.article_id).css({cursor:'pointer','text-decoration':'underline','font-weight':'bold'}).unbind('click').bind('click',getComments).end().find('#imgcomment').replaceWith(img);;
                        }else{
                            img.attr('title','Комментариев нет');
                            com.text(elm.comments).attr('id',elm.article_id).css({cursor:'default','text-decoration':'none','font-weight':'normal'}).unbind('click').end().find('#imgcomment').replaceWith(img);
                            com.text('0');
                        }

                        seg.find('.visibility').attr('id',elm.article_id);
                        seg.find('.views').attr('id','article_'+elm.article_id || 0 ).text(elm.views || 0);
                        seg.find('.countvotes').text(elm.countvote);
                        seg.find('.rating').text(elm.sumscore || 0);
                        var s = seg.find('.score').attr('data-average');

                        if(elm.title.length > 60){
                            elm.title = elm.title.substr(0,60)+'...';
                        }
                        seg.find('.title').text(elm.title);

                        if(resp.length == i+1){
                            for(var c = resp.length;c < 10;c++){
                                $(segment[c]).hide();
                            }
                        }
                        i++;
                    });
                }
            });
        });

        function progressbarAjax(activeCont){

            var cont = activeCont;

            var bar = $('<div>',{id:'progressbar',text:"Загрузка...",style:"top:50%;left:50%;margin-left:-150px;margin-top:-30px;width:250px;height:15px;position:absolute;z-index:999;opacity:1;text-align:center;color:#FFFFFF"});
            cont.css('opacity',0.6);
            $(cont).append(bar);
            $(function() {$( bar ).progressbar({value:true});});
            $(bar)
                .ajaxStart(function(){$(this).show();})
                .ajaxComplete(function(){ $(this).remove();$(cont).css('opacity',1);});
        }
    };
})(jQuery);